public class Solution2369 {

    boolean isValid2(int[] nums, int left, int right){
        if(right - left == 1){
            return nums[left] == nums[right];
        }
        return false;
    }

    boolean isValid3(int[] nums, int left, int right){
        if(right - left == 2){
            if(nums[left] == nums[left + 1] && nums[left] == nums[right]){
                return true;
            }
            if(nums[left] + 1 == nums[left + 1] && nums[left + 1] + 1 == nums[right]){
                return true;
            }
        }
        return false;
    }

    public boolean validPartition(int[] nums) {
        int n = nums.length;
        boolean[] dp = new boolean[n];
        for (int j = 1; j < n; j++) {
            if(j <= 2){
                if(isValid2(nums, 0, j) || isValid3(nums, 0, j)){
                    dp[j] = true;
                }
            } else {
                if(dp[j - 2] && isValid2(nums, j - 1, j)){
                    dp[j] = true;
                }
                if(dp[j - 3] && isValid3(nums, j - 2, j)){
                    dp[j] = true;
                }
            }
        }
        return dp[n - 1];
    }
}
